package org.example.service;

import org.example.entity.User;
import org.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 用户服务类
 */
@Service
@Transactional
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    /**
     * 创建用户
     */
    public User createUser(User user) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (user.getEmail() != null && userRepository.existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        return userRepository.save(user);
    }
    
    /**
     * 根据ID查找用户
     */
    @Transactional(readOnly = true)
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    
    /**
     * 根据用户名查找用户
     */
    @Transactional(readOnly = true)
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    /**
     * 根据邮箱查找用户
     */
    @Transactional(readOnly = true)
    public Optional<User> findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
    
    /**
     * 根据用户名或邮箱查找用户
     */
    @Transactional(readOnly = true)
    public Optional<User> findByUsernameOrEmail(String username, String email) {
        return userRepository.findByUsernameOrEmail(username, email);
    }
    
    /**
     * 更新用户信息
     */
    public User updateUser(User user) {
        try {
            System.out.println("UserService.updateUser - 用户ID: " + user.getId());
            System.out.println("UserService.updateUser - 用户名: " + user.getUsername());
            System.out.println("UserService.updateUser - 密码: " + user.getPassword());
            
            User existingUser = userRepository.findById(user.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            System.out.println("找到现有用户: " + existingUser.getUsername());
            
            // 更新用户名（如果提供）
            if (user.getUsername() != null && !user.getUsername().trim().isEmpty()) {
                existingUser.setUsername(user.getUsername());
                System.out.println("更新用户名: " + user.getUsername());
            }
            
            // 更新基本信息
            if (user.getNickname() != null && !user.getNickname().trim().isEmpty()) {
                existingUser.setNickname(user.getNickname());
                System.out.println("更新昵称: " + user.getNickname());
            }
            if (user.getEmail() != null && !user.getEmail().trim().isEmpty()) {
                existingUser.setEmail(user.getEmail());
                System.out.println("更新邮箱: " + user.getEmail());
            }
            if (user.getPhone() != null && !user.getPhone().trim().isEmpty()) {
                existingUser.setPhone(user.getPhone());
                System.out.println("更新电话: " + user.getPhone());
            }
            if (user.getAvatar() != null && !user.getAvatar().trim().isEmpty()) {
                existingUser.setAvatar(user.getAvatar());
                System.out.println("更新头像: " + user.getAvatar());
            }
            
            // 注意：不更新密码，密码有专门的接口处理
            System.out.println("密码字段不更新，保持原密码");
            
            User updatedUser = userRepository.save(existingUser);
            System.out.println("用户信息更新成功: " + updatedUser.getUsername());
            return updatedUser;
        } catch (Exception e) {
            System.err.println("用户信息更新失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("用户信息更新失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新最后登录时间
     */
    public void updateLastLoginTime(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        userRepository.save(user); // 触发@LastModifiedDate注解更新updated_at字段
    }

    /**
     * 更新密码
     */
    public void updatePassword(Long userId, String oldPassword, String newPassword) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 设置新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
    }
    
    /**
     * 重置密码
     */
    public void resetPassword(Long userId, String newPassword) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);
    }
    
    /**
     * 启用/禁用用户
     */
    public void updateUserStatus(Long userId, Integer status) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        user.setStatus(status);
        userRepository.save(user);
    }
    
    /**
     * 获取所有用户
     */
    @Transactional(readOnly = true)
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }
    
    /**
     * 根据状态查找用户
     */
    @Transactional(readOnly = true)
    public List<User> findUsersByStatus(Integer status) {
        return userRepository.findByStatus(status);
    }
    
    /**
     * 根据昵称搜索用户
     */
    @Transactional(readOnly = true)
    public List<User> searchUsersByNickname(String nickname) {
        return userRepository.findByNicknameContaining(nickname);
    }
    
    /**
     * 统计活跃用户数量
     */
    @Transactional(readOnly = true)
    public long countActiveUsers() {
        return userRepository.countActiveUsers();
    }
    
    /**
     * 删除用户
     */
    public void deleteUser(Long userId) {
        if (!userRepository.existsById(userId)) {
            throw new RuntimeException("用户不存在");
        }
        userRepository.deleteById(userId);
    }

    /**
     * 更新用户角色
     */
    public void updateUserRole(Long userId, String role) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 验证角色是否有效
        try {
            org.example.entity.UserRole.fromString(role);
        } catch (Exception e) {
            throw new RuntimeException("无效的用户角色: " + role);
        }
        
        user.setRole(role);
        userRepository.save(user);
    }

    /**
     * 获取用户使用天数
     */
    @Transactional(readOnly = true)
    public long getUserUsageDays(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return user.getUsageDays();
    }

    /**
     * 获取指定用户的使用天数（到指定日期）
     */
    @Transactional(readOnly = true)
    public long getUserUsageDaysByDate(Long userId, java.time.LocalDateTime targetDate) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return user.getUsageDays(targetDate);
    }
    
    /**
     * 统计所有用户数量
     */
    @Transactional(readOnly = true)
    public long countAllUsers() {
        return userRepository.count();
    }
    
    /**
     * 根据角色统计用户数量
     */
    @Transactional(readOnly = true)
    public long countByRole(String role) {
        return userRepository.countByRole(role);
    }
    
}
